var express = require('express');
var router = express.Router();
const Arweave = require('arweave');

const arweave = Arweave.init({
    host: 'arweave.net',
    port: 443,
    protocol: 'https'
});


/**
 * 交易签名
 */
router.post('/generate', function (req, res) {
    generate().then((tx) => {
        res.set('Content-Type', 'application/json');
        res.status(200).send(JSON.stringify(tx));
    });
});

router.post('/getaddress', function (req, res) {
    jwkToAddress(req.body).then((tx) => {
        res.set('Content-Type', 'application/json');
        console.log(tx)
        res.status(200).send('{\"result\":\"' + tx + '\"}');
    });
});

router.post('/sendTransaction', function (req, res) {
    const params = req.body;
    sendTransaction(params.wallet,params.quantity,params.target).then((tx) => {
        res.set('Content-Type', 'application/json');
        console.log(tx)
        res.status(200).send('{\"result\":\"' + tx + '\"}');
    });
});

/**
 * 获取签名
 */
async function generate() {
    return await arweave.wallets.generate();
}

/**
 * 根据签名获取地址
 * @param jwk
 * @returns {Promise<string>}
 */
async function jwkToAddress(jwk) {
    return await arweave.wallets.jwkToAddress(jwk);
}

/**
 *
 * @param wallet
 * @param quantity 数量字符串
 * @param target to地址
 * @returns {Promise<string>}
 */
async function sendTransaction(wallet,quantity,target){
    const address = await arweave.wallets.jwkToAddress(wallet);
    console.log(address)
    const transaction = await arweave.createTransaction(
        {
            target: target,
            quantity: quantity
        },
        wallet
    );
    await arweave.transactions.sign(transaction, wallet);
    console.log(transaction)
    const response = await arweave.transactions.post(transaction);
    console.log(response)
    if (response.status === 200) {
        return transaction.id;
    }
    return null;
}


module.exports = router;
